import React, { useEffect, useState, useRef, Fragment } from 'react';
import { Form, Card, Table, Button, Spin } from 'antd';
import { utils } from 'vv-frontend-components';
import { eventTrack } from '@/utils/track';
import { connect } from 'umi';
import { Link }  from 'umi';
import moment from 'moment';
import { stringify } from 'qs';
import { history } from 'umi';
import cn from 'classnames';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TableFilter from '@/components/TableFilter';
import withClearState from '@/utils/withClearState';
import { pathNameMap } from '@/utils/dictionary';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import authHelper from '@/utils/auth/helper';
import LinkTo from '@/components/LinkTo';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageRouter from '@/components/PageRouter/PageRouter';
import routerReplace from '@/utils/routerReplace';
import Pagination from '@/components/Pagination';
import SearchForm from './part/SearchForm';
import Manipulate from './part/FormModal';
// import { findCountry } from './part/utils';
import styles from '../RecruitMange.less';

const { deepTrim } = utils;
const { checkCode } = authHelper;

/**
 * 招聘需求--企业列表、招聘需求--用人部门列表、招聘需求--我的招聘任务列表 写在一个页面里
 * 根据 定义字典判断 当前的页面  see: src\utils\dictionary.js
 * isUser 用人部门页面
 * isHR HR页面
 */
const PositionList = props => {
    const { positionManage = {}, dispatch, form, route, location, loading } = props;
    const { getFieldsValue } = form;
    const { pathname, query } = location;

    const { positionPagination: pagination, positionList, recruitScheduleType, orderBy, applyData } = positionManage;

    const { authCode } = new AuthCode(route.code); // 权限code校验工具
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};

    /** 根据定义字典判断 当前的页面 */
    const currentRouteInfo = pathNameMap.find(v => v.pathName === pathname);
    const {
        isUser = null, // 用人部门必传
        isHR = null, // HR必传
        code: privateCode, // 临时处理我的招聘页面的权限
        ...otherPath
    } = currentRouteInfo;

    const [collapsed, setCollapsed] = useState(true);
    const isFirstRun = useRef(true);
    const [schedule, setSchedule] = useState(query.schedule ? [query.schedule] : []);
    const [sorterInfo, setSorterInfo] = useState();
    const [filtersInfo, setFiltersInfo] = useState();

    // 操作项弹窗
    const ManipulateRef = useRef(null);
    const extraButton = (
        <Button
            type="primary"
            onClick={async () => {
                const pageTrack = JSON.parse(localStorage.getItem('pageTrack') || '{}');
                const { pageName } = pageTrack;
                await eventTrack({
                    eventName:
                        pageName === '招聘职位 - 微微科技集团管理系统'
                            ? 'personnel_management_recruit_position_apply_click'
                            : 'personal_my_recruit_task_apply_click',
                    eventProps:
                        pageName === '招聘职位 - 微微科技集团管理系统'
                            ? { label: '招聘职位-发起招聘申请' }
                            : { label: '我的招聘任务-发起招聘申请' }
                });
                history.push({
                    pathname: '/personal/portal/flow/mine/list/apply',
                    query: {
                        templateId: applyData.id,
                        processDeploymentId: applyData.processDeploymentId,
                        formDeploymentId: applyData.formDeploymentId,
                        templateName: applyData.templateName
                    }
                });
            }}
        >
            发起招聘申请
        </Button>
    );

    /**
     * 获取卡片头部信息
     */
    const cardProps = isPageRouter => {
        const result = {
            title: isPageRouter ? null : otherPath.remark,
            extra: isHR || isPageRouter ? null : extraButton
        };
        return result;
    };

    /**
     * 根据路由配置信息，生成表格操作项
     */
    const getActionLink = (text, record) => {
        const params = {
            recruitCode: record.recruitCode,
            companyId: record.companyId,
            applicationNo: record.applicationNo
        };
        if (isUser) {
            return (
                <React.Fragment>
                    <AuthComponent code={privateCode || authCode('detail')}>
                        <Link to={`${pathname}/positiondetails?${stringify(params)}`}>详情</Link>
                    </AuthComponent>
                </React.Fragment>
            );
        }
        return (
            <React.Fragment>
                <AuthComponent code={privateCode || authCode('detail')}>
                    <Link
                        onClick={async () => {
                            // 埋点
                            const pageTrack = JSON.parse(localStorage.getItem('pageTrack') || '{}');
                            const { pageName } = pageTrack;
                            await eventTrack({
                                eventName:
                                    pageName === '招聘职位 - 微微科技集团管理系统'
                                        ? 'personnel_management_recruit_position_operator_click'
                                        : 'null',
                                eventProps:
                                    pageName === '招聘职位 - 微微科技集团管理系统'
                                        ? { label: '招聘职位-操作-详情' }
                                        : null
                            });
                        }}
                        to={`${pathname}/positiondetails?${stringify(params)}`}
                    >
                        详情
                    </Link>
                </AuthComponent>
                <AuthComponent code={privateCode || authCode('set')}>
                    {(privateCode || checkCode(authCode('detail'))) && (
                        <span
                            style={{
                                color: '#EBEEF5',
                                margin: '0px 5px'
                            }}
                        >
                            |
                        </span>
                    )}
                    <a
                        style={{ display: 'inline-block' }}
                        onClick={async () => {
                            const pageTrack = JSON.parse(localStorage.getItem('pageTrack') || '{}');
                            const { pageName } = pageTrack;
                            ManipulateRef.current.show({
                                recruitCode: record.recruitCode,
                                companyId: record.companyId
                            });
                            await eventTrack({
                                // 埋点
                                eventName:
                                    pageName === '招聘职位 - 微微科技集团管理系统'
                                        ? 'personnel_management_recruit_position_operator_click'
                                        : 'null',
                                eventProps:
                                    pageName === '招聘职位 - 微微科技集团管理系统'
                                        ? { label: '招聘职位-操作-设置' }
                                        : null
                            });
                        }}
                    >
                        设置
                    </a>
                </AuthComponent>
            </React.Fragment>
        );
    };

    /**
     * 获取页面查询参数
     */
    const getParams = ({ pageNo, pageSize, orderByField }) => {
        const {
            shenqing = [], // 申请时间
            // leixingzhiwei = {}, // 类型职级
            companyDepart = {}, // 公司部门
            leaderIds = [],
            ...params
        } = getFieldsValue();
        // console.log('getParams -> leixingzhiwei', leixingzhiwei);
        // console.log(getFieldsValue(), 'getFieldsValue');
        // const tmppostType = leixingzhiwei.postType ? leixingzhiwei.postType.split('-') : [''];
        const payload = {
            ...params,
            leaderIds,
            companyId: companyDepart.companyId || '',
            departmentId: companyDepart.departmentId || '',
            startTime: shenqing[0] ? shenqing[0].format('YYYY-MM-DD ') : '',
            endTime: shenqing[1] ? shenqing[1].format('YYYY-MM-DD') : '',
            // postTypeRemark: leixingzhiwei.postTypeRemark,
            // postRank: leixingzhiwei.postRank,
            // postType: tmppostType[0],
            schedule: schedule.join(),
            orderByField: orderByField || orderBy,
            userCode: isUser ? user.userCode : '',
            employeeCode: isHR ? user.employeeCode : '',
            pageNo: pageNo || pagination.current,
            pageSize: pageSize || pagination.pageSize
        };
        return payload;
    };

    /**
     * 获取列表页数据
     */
    const fetchList = (ctx = {}) => {
        const { pageNo = null, pageSize = null, orderByField } = ctx;
        dispatch(
            deepTrim({
                type: 'positionManage/fetchList',
                payload: getParams({ pageNo, pageSize, orderByField }),
                dictionary: {
                    pathName: pathname
                }
            })
        );
    };
    /** 获取招聘进度字典 */
    const fetchTypeList = () => {
        dispatch({
            type: 'positionManage/fetchTypeList',
            payload: { dictCode: 'recruitScheduleType' }
        });
    };
    /** 获取发起招聘需要的值 */
    const fetchApply = () => {
        dispatch({
            type: 'positionManage/fetchApply',
            payload: { companyId: user.companyId }
        });
    };
    // const reducer = async (pageSize = 10) => {
    //     await dispatch({
    //         type: 'positionManage/save',
    //         payload: {
    //             positionPagination: {
    //                 ...pagination,
    //                 pageSize,
    //                 current: 1
    //             }
    //         }
    //     });
    // };
    const defaultSort = type => {
        const { orderByField = '' } = query;
        const str = orderByField ? orderByField.replace(type, '').trim() : '';
        if (str === 'asc') {
            return 'ascend';
        }
        if (str === 'desc') {
            return 'descend';
        }
        return false;
    };
    const tableColumns = () => {
        const baseColums = [
            {
                title: '招聘职位',
                dataIndex: 'recruitPost',
                className: styles.nowrap,
                width: 200,
                fixed: 'left',
                render: (text, record) => {
                    const params = {
                        recruitCode: record.recruitCode,
                        companyId: record.companyId,
                        applicationNo: record.applicationNo
                    };
                    const flag = privateCode || checkCode(authCode('detail'));
                    return (
                        <Fragment>
                            <LinkTo
                                onClick={async (e, url) => {
                                    await eventTrack({
                                        eventName: 'personnel_management_recruit_position_detail_click',
                                        eventProps: {
                                            label: '招聘职位-职位详情'
                                        }
                                    });
                                    history.push(url);
                                }}
                                className={cn({
                                    [styles.disabled]: !flag,
                                    [styles.nowrap]: true,
                                    [styles.title]: true
                                })}
                                title={text}
                                to={`${pathname}/positiondetails`}
                                query={params}
                            >
                                {text}
                            </LinkTo>
                            <br />
                            <div className={styles.nowrap} title={`${record.companyName}|${record.departmentName}`}>
                                {record.companyName}
                                {record.departmentName && (
                                    <Fragment>
                                        <span
                                            style={{
                                                color: 'rgba(0,0,0,0.65)',
                                                margin: '0px 5px',
                                                fontSize: '12px'
                                            }}
                                        >
                                            |
                                        </span>
                                        {record.departmentName}
                                    </Fragment>
                                )}
                            </div>
                        </Fragment>
                    );
                }
            },
            {
                title: '职级',
                dataIndex: 'postRank',
                width: 200,
                fixed: 'left',
                render: text => (
                    <div
                        className={cn({
                            [styles.nowrap]: true,
                            [styles.ellipsis]: true
                        })}
                    >
                        {text}
                    </div>
                )
            },
            {
                title: '申请时间',
                dataIndex: 'applyDate',
                width: 200,
                sorter: () => {},
                sortOrder: defaultSort('apply_date'),
                render(text, record) {
                    if (record.applyDate === '') {
                        return (
                            <div className={styles.nowrap} title={text}>
                                <span>--</span>
                            </div>
                        );
                    }
                    return (
                        <div
                            className={cn({
                                [styles.nowrap]: true,
                                [styles.ellipsis]: true
                            })}
                            title={text}
                        >
                            <span>{record.applyDate}</span>
                        </div>
                    );
                }
            },
            {
                title: '紧急程度',
                dataIndex: 'necessaryName',
                className: styles.nowrap,
                width: 200
                // render: text => '123'
            },
            {
                title: '需求数',
                dataIndex: 'requireNums',
                width: 200,
                sorter: () => {},
                sortOrder: defaultSort('require_nums'),
                render: text => (
                    <div className={styles.nowrap} title={text} style={{ width: '150px' }}>
                        {text}
                    </div>
                )
            },
            {
                title: '招聘进度',
                dataIndex: 'schedule',
                width: 200,
                filters: recruitScheduleType,
                filteredValue: schedule,
                filterMultiple: false,
                filterDropdown: filterProps => <TableFilter {...filterProps} />,
                render(text) {
                    let isOver = '';
                    recruitScheduleType.forEach(item => {
                        if (item.value === text) {
                            isOver = item.text;
                        }
                    });
                    return (
                        <div
                            className={cn({
                                [styles.nowrap]: true,
                                [styles.ellipsis]: true
                            })}
                            title={text}
                        >
                            <span style={{ color: 'dictColor[text]' }}>{isOver}</span>
                        </div>
                    );
                }
            },
            {
                title: '招聘负责人',
                dataIndex: 'leaderName',
                width: 200,
                render: text => (
                    <div
                        className={cn({
                            [styles.nowrap]: true,
                            [styles.ellipsis]: true
                        })}
                        title={text}
                    >
                        {text}
                    </div>
                )
            },
            {
                title: '业务负责人',
                dataIndex: 'servicePersonName',
                // width: 200,
                render: text => (
                    <div
                        className={cn({
                            [styles.nowrap]: true,
                            [styles.ellipsis]: true
                        })}
                        title={text}
                    >
                        {text}
                    </div>
                )
            }
        ];
        const footerColums = [
            {
                title: '操作',
                dataIndex: 'actionLink',
                fixed: 'right',
                // align: 'center',
                width: 200,
                render(text, record) {
                    return <div style={{ whiteSpace: 'nowrap' }}>{getActionLink(text, record)}</div>;
                }
            }
        ];
        // 我的招聘任务
        if (isHR) {
            baseColums.splice(5, 1);
        }
        // 我的招聘需求
        if (isUser) {
            baseColums.splice(6, 1);
        }
        return baseColums.concat(footerColums);
    };
    const tableChange = async (paginations, filters, sorter) => {
        const extra = {};
        if (filtersInfo !== filters) {
            extra.current = 1;
            setFiltersInfo(filters);
        }
        if (sorterInfo !== sorter) {
            extra.current = 1;
            setSorterInfo(sorter);
        }
        let newOrderBy = null;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'applyDate') {
                sorterField = 'apply_date';
            }
            if (sorter.field === 'requireNums') {
                sorterField = 'require_nums';
            }
            const order = sorter.order.trim().split('end')[0];
            newOrderBy = `${sorterField} ${order}`;
        }
        setSchedule(filters && filters.schedule ? filters.schedule : []);
        await dispatch({
            type: 'positionManage/save',
            payload: {
                orderBy: newOrderBy || '',
                positionPagination: {
                    ...positionManage.positionPagination,
                    ...paginations,
                    ...extra
                }
            }
        });
        const { leaderIds, ...params } = getParams({ pageNo: 1 });
        const { current, pageSize } = paginations;
        const temp = {};
        if (current) {
            temp.pageNo = current;
        }
        if (pageSize) {
            temp.pageSize = pageSize;
        }
        routerReplace({
            query: {
                ...params,
                ...temp,
                leaderIds: leaderIds.length > 0 ? leaderIds : '',
                orderByField: newOrderBy,
                schedule: filters ? filters.schedule : []
            }
        });
    };
    const paginationChange = async paginations => {
        await dispatch({
            type: 'positionManage/save',
            payload: {
                positionPagination: {
                    ...positionManage.positionPagination,
                    ...paginations
                }
            }
        });
        const { leaderIds, ...params } = getParams({ pageNo: 1 });
        const { current, pageSize } = paginations;
        const temp = {};
        if (current) {
            temp.pageNo = current;
        }
        if (pageSize) {
            temp.pageSize = pageSize;
        }
        routerReplace({
            query: {
                ...params,
                ...temp,
                leaderIds: leaderIds.length > 0 ? leaderIds : ''
            }
        });
    };

    const initCollapsed = () => {
        if (query.companyId) {
            setCollapsed(false);
        }
    };

    // TODO 合并多个异步请求
    const init = orderByField => {
        initCollapsed();
        fetchApply();
        fetchTypeList();
        const obj = {};
        if (query.pageNo) {
            obj.pageNo = query.pageNo;
        }
        if (query.pageSize) {
            obj.pageSize = query.pageSize;
        }
        fetchList({ orderByField, ...obj });
    };
    /**
     * 头部表单查询
     */
    const handleSubmit = async isReset => {
        const { leaderIds, ...params } = getParams({ pageNo: 1 });
        routerReplace({ query: { ...params, leaderIds: leaderIds.length > 0 ? leaderIds : '' } });
        fetchList({ pageNo: 1 });
        // 埋点
        if (isReset) {
            eventTrack({
                eventName: isHR ? 'personal_my_recruit_task_reset_click' : 'personal_my_recruit_demand_reset_click'
            });
        } else {
            eventTrack({
                eventName: isHR ? 'personal_my_recruit_task_operator_click' : 'personal_my_recruit_demand_reset_click',
                eventProps: {
                    keyword: JSON.stringify(params)
                }
            });
        }
    };
    const handleReset = () => {
        // reducer();
        const isReset = true;
        handleSubmit(isReset);
    };
    useEffect(() => {
        const {
            companyId,
            departmentId,
            endTime,
            leaderIds,
            orderByField,
            // postRank,
            // postTypeRemark,
            // postType,
            recruitPost,
            servicePersonId,
            startTime,
            postGradeCodeList
        } = query;
        if (recruitPost) {
            form.setFieldsValue({
                recruitPost
            });
        }
        if (startTime && endTime) {
            form.setFieldsValue({
                shenqing: [moment(startTime), moment(endTime)]
            });
        }
        if (companyId || departmentId) {
            form.setFieldsValue({
                companyDepart: {
                    companyId: companyId || user.companyId || undefined,
                    departmentId: departmentId || undefined
                }
            });
        }
        // if (postType || postRank || postTypeRemark) {
        //     form.setFieldsValue({
        //         leixingzhiwei: {
        //             postTypeRemark,
        //             postType,
        //             postRank
        //         }
        //     });
        // } else {
        //     const country = findCountry(user.companyId);
        //     form.setFieldsValue({
        //         leixingzhiwei: {
        //             postTypeRemark: (country && country.postTypeRemark) || 'GroupRecruitPostType'
        //         }
        //     });
        // }
        if (servicePersonId) {
            form.setFieldsValue({
                servicePersonId: Number(servicePersonId)
            });
        }
        if (leaderIds) {
            const arr = leaderIds.split(',').map(item => {
                if (typeof item === 'string') {
                    return Number(item);
                }
                return item;
            });
            form.setFieldsValue({
                leaderIds: arr
            });
        }
        if (postGradeCodeList) {
            form.setFieldsValue({
                postGradeCodeList: postGradeCodeList.split(',')
            });
        }
        if (orderByField) {
            init(orderByField);
        } else {
            init();
        }
    }, []);
    useEffect(() => {
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        // form.setFieldsValue(query);
        fetchList();
    }, [orderBy, pagination.pageSize, pagination.current, schedule]);

    return (
        <PageHeaderWrapper>
            <PageRouter type="myrecruit" extraButton={isHR && extraButton}>
                {isPageRouter => (
                    <Card {...cardProps(isPageRouter)} bordered={false}>
                        <Spin spinning={loading}>
                            <SearchForm
                                form={form}
                                query={query}
                                user={user}
                                collapsed={collapsed}
                                reset={() => handleReset()}
                                submit={() => handleSubmit()}
                                setCollapsed={setCollapsed}
                                isUser={isUser}
                                isHR={isHR}
                            />
                            <Table
                                columns={tableColumns()}
                                dataSource={positionList}
                                onChange={tableChange}
                                bordered={false}
                                rowKey="id"
                                scroll={{ x: 'max-content' }}
                                pagination={false}
                            />
                            <Pagination
                                {...pagination}
                                onChange={paginationChange}
                                filters={filtersInfo}
                                sorter={sorterInfo}
                            />
                        </Spin>
                        <Manipulate wrappedComponentRef={ManipulateRef} location={location} onOk={() => fetchList()} />
                    </Card>
                )}
            </PageRouter>
        </PageHeaderWrapper>
    );
};
const mapStateToProps = ({ positionManage, loading }) => ({
    positionManage,
    loading: loading.global
});
export default withRoutePage(connect(mapStateToProps)(withClearState('positionManage')(Form.create()(PositionList))));
